package com.yachang.qym.usbhost.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.baidu.platform.comapi.map.A;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.activity.CallingActivity;
import com.yachang.qym.usbhost.activity.HelpActivity;
import com.yachang.qym.usbhost.activity.MainActivity;
import com.yachang.qym.usbhost.model.CallHelpModel;
import com.yachang.qym.usbhost.model.HelpModel;
import com.yachang.qym.usbhost.usbserial.driver.UsbSerialDriver;
import com.yachang.qym.usbhost.usbserial.driver.UsbSerialPort;
import com.yachang.qym.usbhost.usbserial.driver.UsbSerialProber;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.DataTransfer;
import com.yachang.qym.usbhost.utils.DeveloperData;
import com.yachang.qym.usbhost.utils.LoadImage;
import com.yachang.qym.usbhost.utils.LogUtil;
import com.yachang.qym.usbhost.utils.NotificationCenter;
import com.yachang.qym.usbhost.utils.SendData;
import com.yachang.qym.usbhost.utils.ToastUtil;
import com.yachang.qym.usbhost.utils.VoiceUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by qinyuanmao on 16/3/4.
 */
public class GetDataService extends Service{

    private byte[] getBuffer = new byte[0];
    private DataTransfer mDataTransfer = new DataTransfer(1024);
    private boolean threadCt = false;
    private boolean dataCt = false;
    private GetDataThread thread;

    private byte[] sendBuffer;

    private UsbManager manager;
    private UsbSerialPort sPort;
    private int timerCount = 0;
    private boolean firstRecode = true;
    private double lastFloor = 0;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                /*case 0: {
                    Intent intent = new Intent(GetDataService.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }break;*/
                case 1: {
                    Intent intent = new Intent(GetDataService.this, CallingActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }break;
                case 2: {
                    NotificationCenter.getInstance().postNotification("changeHelpState");
                }break;
                case 3:{
                    CallHelpModel model = new CallHelpModel();
                    for(int i = 0; i < AllData.outPoliceModels.size(); i++){
                        if(AllData.outPoliceModels.get(i).getMid().equals(AllData.callHelpId)){
                            model.setUid(AllData.outPoliceModels.get(i).getUid());
                            model.setHigh(AllData.outPoliceModels.get(i).getHigh());
                            model.setName(AllData.outPoliceModels.get(i).getUserName());
                            model.setUserImage(AllData.outPoliceModels.get(i).getUserImage());
                            model.setFid(AllData.outPoliceModels.get(i).getFid());
                            model.setMid(AllData.callHelpId);
                            model.setOid(AllData.outPoliceModels.get(i).get_id());
                            break;
                        }
                    }
                    if(!AllData.isToHelp)
                        showNotification(model);
                }break;
                case 4:{
                    String str = (String) msg.obj;
                    if(str.equals(AllData.helpModel.getMachineID())){
                        AllData.isToHelp = true;
                        ToastUtil.showToast("已进入搜救模式，请返回到主页搜救页面！");

                        /*Map<String, Object> map = new HashMap<String, Object>();
                        map.put("helperoid", AllData.outPolice_id);
                        map.put("helperId", AllData.userModel.get_id());
                        map.put("helperImage", AllData.userModel.getImageUrl());
                        map.put("helperName", AllData.userModel.getUsername());
                        map.put("uid", AllData.helpActivityData.getUid());
                        map.put("mid", AllData.helpActivityData.getMid());
                        map.put("oid", AllData.helpActivityData.getOid());
                        map.put("high", AllData.helpActivityData.getHigh());
                        map.put("fid", AllData.helpActivityData.getFid());
                        map.put("name", AllData.helpActivityData.getName());
                        map.put("image", AllData.helpActivityData.getUserImage());
                        JSONObject jsonObject = new JSONObject(map);

                        API.mSocket.emit("helperAdd", jsonObject);*/
                        break;
                    } else {
                        for(int i = 0; i < AllData.outPoliceModels.size(); i++){
                            if(AllData.outPoliceModels.get(i).getMid().equals(str)){
                                ToastUtil.showToast("该呼救人员" + AllData.outPoliceModels.get(i).getUserName() + "已经去救了!");
                                break;
                            }
                        }
                    }
                }break;
                default: break;
            }
        }
    };

    private void showNotification(CallHelpModel model){
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(UsbApplication.getContext())
                        .setSmallIcon(R.mipmap.icon)
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .setContentTitle("求救人："+ model.getName())
                        .setContentText("所在高度：" + model.getHigh()+"")
                        .setDefaults(Notification.DEFAULT_ALL);
        mBuilder.setLargeIcon(AllData.userBitmap.get(model.getUid()));
        Intent intent = new Intent(this, HelpActivity.class);
        intent.putExtra("model", model);
        PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
        mBuilder.setContentIntent(pendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) UsbApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(Integer.parseInt(model.getMid()), mBuilder.build());
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
        };
    };

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        connectUsb();
        threadCt = true;
        if(sPort == null){
            Toast.makeText(this, "设备连接异常！", Toast.LENGTH_SHORT).show();
        } else {
            thread = new GetDataThread();
            thread.start();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        threadCt = false;
        super.onDestroy();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(timerCount != 300) {
                if (DataTransfer.getNum(AllData.helpModel.getMachineHigh()) - AllData.FIRST_HIGH > 3) {
                    AllData.FIRST_HIGH = DataTransfer.getNum(AllData.helpModel.getMachineHigh());
                    timerCount = 0;
                } else {
                    timerCount++;
                }
            } else {
                AllData.VECTOR_HIGH = DataTransfer.getNum(AllData.helpModel.getMachineHigh()) - AllData.FIRST_HIGH;
            }
            handler.postDelayed(runnable, 1000);
        }
    };

    private void connectUsb(){
        if (MainActivity.sPort == null) {
            manager = (UsbManager) getSystemService(Context.USB_SERVICE);
            final List<UsbSerialDriver> drivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);

            if (!drivers.isEmpty()) {
                UsbSerialDriver driver = drivers.get(0);
                UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
                sPort = driver.getPorts().get(0);

                if (connection == null) {
                    Toast.makeText(this, "设备连接异常！", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        if (sPort != null) {
                            sPort.open(connection);
                            sPort.setParameters(38400, 8, UsbSerialPort.STOPBITS_2, UsbSerialPort.PARITY_NONE);
                        } else {
                            Toast.makeText(this, "未找到设备，请检查连接", Toast.LENGTH_SHORT).show();
                        }
                    } catch (IOException e) {
                        try {
                            sPort.close();
                        } catch (IOException e2) {

                        }
                        sPort = null;
                    }
                }
            } else {
                Toast.makeText(this, "未找到设备，请检查连接", Toast.LENGTH_SHORT).show();
            }
        } else {
            sPort = MainActivity.sPort;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    class GetDataThread extends Thread{

        public void run(){
            while (threadCt) {
                if (SendData.needSend) {
                    SendData.needSend = false;
                    sendBuffer = SendData.data;
                    try {
                        sPort.write(sendBuffer, 30);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                byte[] buffer = new byte[256];
                int dataLength = 0;
                try {
                    dataLength = sPort.read(buffer, buffer.length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (dataLength > 0) {
                    getData(buffer, dataLength);
                }
            }
        }

        public void getData(byte[] buffer, int dataLength) {

            mDataTransfer.AddData(buffer, dataLength);
            byte[] newBuffer = new byte[mDataTransfer.GetDataLen()];
            mDataTransfer.ReadMultiData(newBuffer, mDataTransfer.GetDataLen());

            byte[] data = new byte[getBuffer.length + newBuffer.length];
            System.arraycopy(getBuffer, 0, data, 0, getBuffer.length);
            System.arraycopy(newBuffer, 0, data, getBuffer.length, newBuffer.length);
            getBuffer = data;

           // LogUtil.LogByte(getBuffer);

            if(getBuffer.length >= 3) {
                int byte0 = (int) getBuffer[0] > 0 ? (int) getBuffer[0] : (int) getBuffer[0] + 256;
                int byte1 = (int) getBuffer[1] > 0 ? (int) getBuffer[1] : (int) getBuffer[1] + 256;
                int byte2 = (int) getBuffer[2] > 0 ? (int) getBuffer[2] : (int) getBuffer[2] + 256;
                if (byte0 != 0x84 && byte1 != 0xA9 && byte2 != 61) {
                    getBuffer = new byte[0];
                } else {
                    if ((getBuffer[getBuffer.length - 2] == 0x0D) && (getBuffer[getBuffer.length - 1] == 0x0A) && (getBuffer[4] == 0x00)) {
                        int whatData = ((int) getBuffer[6]) > 0 ? ((int) getBuffer[6]) : ((int) getBuffer[6]) + 256;
                        if (whatData == 0xCD) {
                            try {
                                AllData.helpModel = DataTransfer.getHelpInfo(getBuffer, (int) getBuffer[7]);
                                double nowFloor = (DataTransfer.getNum(AllData.helpModel.getMachineHigh()) - AllData.VECTOR_HIGH) / AllData.FLOOR_HIGH;
                                if(lastFloor > 0 && nowFloor < 0){
                                    nowFloor = nowFloor + AllData.FIRST_FLOOR - 1;
                                } else if(lastFloor < 0 && nowFloor > 0){
                                    nowFloor = nowFloor + AllData.FIRST_FLOOR + 1;
                                } else {
                                    nowFloor = nowFloor + AllData.FIRST_FLOOR;
                                }
                                BigDecimal b = new BigDecimal(nowFloor);
                                nowFloor = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
                                //AllData.helpModel.setNowFloor(nowFloor);
                                HelpModel.needChange = true;
                                if(firstRecode){
                                    handler.postDelayed(runnable, 1000);
                                    firstRecode = false;
                                } else {
                                    AllData.helpModel.setNowFloor(nowFloor);
                                }
                                lastFloor = nowFloor;
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            getBuffer = new byte[0];
                        } else if (whatData == 0xC9) {
                            DeveloperData.debugData = DataTransfer.getDebugData(getBuffer);
                            DeveloperData.needChange = true;
                            getBuffer = new byte[0];
                        } else if(whatData == 0xDF){
                            AllData.isToHelp = false;
                            getBuffer = new byte[0];
                        } else if(whatData == 0xDA){
                            byte[] helpMid = new byte[3];
                            for(int i = 0; i < 3; i++){
                                int num = ((int) getBuffer[i + 7]) > 0 ? ((int) getBuffer[i + 7]) : ((int) getBuffer[i + 7]) + 256;
                                helpMid[i] = (byte) num;
                            }
                            AllData.callHelpId = DataTransfer.bytesToInt(helpMid) + "";
                            LogUtil.LogByte(helpMid);
                            Message message = new Message();
                            message.what = 3;
                            handler.sendMessage(message);
                            getBuffer = new byte[0];
                        } else if(whatData == 0xDC){
                            byte[] helpMid = new byte[3];
                            for(int i = 0; i < 3; i++){
                                int num = ((int) getBuffer[i + 7]) > 0 ? ((int) getBuffer[i + 7]) : ((int) getBuffer[i + 7]) + 256;
                                helpMid[i] = (byte) num;
                            }
                            String str = DataTransfer.bytesToInt(helpMid) + "";
                            Message message = new Message();
                            message.what = 4;
                            message.obj = str;
                            handler.sendMessage(message);
                            getBuffer = new byte[0];
                        } else {
                            getBuffer = new byte[0];
                        }
                    } else if (getBuffer.length >= 10) {
                        int bufferDataLength = ((int) getBuffer[4]) > 0 ? ((int) getBuffer[4]) : (((int) getBuffer[4]) + 256);
                        if (getBuffer.length >= bufferDataLength + 5) {
                            if (getBuffer.length >= 10 && getBuffer.length < 18) {
                                int whatData = ((int) getBuffer[6]) > 0 ? ((int) getBuffer[6]) : ((int) getBuffer[6]) + 256;
                                if (whatData == 0xCF) {
                                    try {
                                        AllData.nowRoute = DataTransfer.getNowRoute(getBuffer);
                                        AllData.nowRouteNeedChange = true;
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                } else if (whatData == 0xBF) {
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                } else if (whatData == 0xCB) {
                                    if (AllData.isFirst) {
                                        int byte7 = ((int) getBuffer[7]) >= 0 ? ((int) getBuffer[7]) : (((int) getBuffer[7]) + 256);
                                        AllData.voice = byte7;
                                        AllData.isFirst = false;
                                    }
                                } else if (whatData == 0xCC) {
                                    DeveloperData.lastEle = ((int) getBuffer[7]) >= 0 ? ((int) getBuffer[7]) : (((int) getBuffer[7]) + 256);
                                    DeveloperData.needChange = true;
                                } else if (whatData == 0xCE) {
                                    byte[] newData = DataTransfer.getHelpInfoByte(getBuffer, 7, (byte) 0x2F);
                                    try {
                                        DeveloperData.nowEle = new String(newData, "ascii").trim();
                                        DeveloperData.needChange = true;
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                } else if (whatData == 0xCA) {
                                    byte[] newData = DataTransfer.getHelpInfoByte(getBuffer, 7, (byte) 0x2F);
                                    try {
                                        DeveloperData.allEle = new String(newData, "ascii").trim();
                                        DeveloperData.needChange = true;
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                } else if ((whatData == 0xCD) && (getBuffer[7] == 2)) {
                                    if((getBuffer[8]) == 0x00 && (AllData.needHelp)){
                                        AllData.needHelp = false;
                                        Message message = new Message();
                                        message.what = 2;
                                        handler.sendMessage(message);
                                    } else if((getBuffer[8] == 0x01) && (!AllData.needHelp)){
                                        AllData.needHelp = true;
                                        Message message = new Message();
                                        message.what = 2;
                                        handler.sendMessage(message);
                                    }
                                }
                            } else if (getBuffer.length >= 18) {
                                int whatData = ((int) getBuffer[6]) > 0 ? ((int) getBuffer[6]) : ((int) getBuffer[6]) + 256;
                                if (whatData == 0x88) {
                                    VoiceUtil.isNormal = false;
                                    if (getBuffer[9] == 0x01 && getBuffer[10] == 0x01) {
                                        byte[] id = new byte[4];
                                        for (int i = 0; i < 4; i++) {
                                            id[i] = getBuffer[i + 11];
                                        }
                                        VoiceUtil.setID(id);
                                        VoiceUtil.style = getBuffer[15];
                                        byte[] mid = new byte[4];
                                        for(int i = 0; i < 4; i++){
                                            mid[i] = getBuffer[i + 16];
                                        }
                                        VoiceUtil.mid = DataTransfer.getTenNum(mid) + "";
                                        VoiceUtil.whatIsDoing = VoiceUtil.IS_LISTEN;
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    } else if (getBuffer[9] == 0x01 && getBuffer[10] == 0x03) {
                                        VoiceUtil.setID(new byte[4]);
                                        VoiceUtil.whatIsDoing = VoiceUtil.IS_LISTEN_FINISH;
                                    } else if (getBuffer[9] == 0x02 && getBuffer[10] == 0x01) {
                                        byte[] id = new byte[4];
                                        for (int i = 0; i < 4; i++) {
                                            id[i] = getBuffer[i + 11];
                                        }
                                        VoiceUtil.setID(id);
                                        VoiceUtil.whatIsDoing = VoiceUtil.IS_SPEAK;
                                        VoiceUtil.style = getBuffer[15];
                                        byte[] mid = new byte[4];
                                        for(int i = 0; i < 4; i++){
                                            mid[i] = getBuffer[i + 16];
                                        }
                                        VoiceUtil.mid = DataTransfer.getTenNum(mid) + "";
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    } else if (getBuffer[9] == 0x02 && getBuffer[10] == 0x03) {
                                        VoiceUtil.setID(new byte[4]);
                                        VoiceUtil.whatIsDoing = VoiceUtil.IS_SPEAK_FINISH;
                                    } else {
                                        VoiceUtil.isNormal = true;
                                    }
                                }
                            }
                            getBuffer = new byte[0];
                        }
                    }
                    if (getBuffer.length > 200) {
                        getBuffer = new byte[0];
                    }
                }
            }
        }
    }
}
